package com.jiangyg.devtools.ui.table.cell;

import com.intellij.ide.util.PackageChooserDialog;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiPackage;
import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;

import javax.swing.*;
import java.awt.*;
import java.util.EventObject;

/**
 * 类描述：包选择器单元格编辑器
 *
 * @author jiangyg
 * @version 1.0
 * @date 2023年08月29日
 */
public class PackageChooserCellEditor extends AbstractTableCellEditor {

    private final JBLabel component = new JBLabel();

    private String path;

    public PackageChooserCellEditor(Project project) {
        super(project);

        component.setForeground(JBColor.getHSBColor(108, 66, 66));
        UIUtil.addInsets(component, JBUI.insets(0, 10));
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
                                                 Object value,
                                                 boolean isSelected,
                                                 int rowIndex, int columnIndex) {
        final String string = String.valueOf(value);

        component.setText(string);
        component.setToolTipText(string);

        return component;
    }

    @Override
    public boolean shouldSelectCell(EventObject anEvent) {
        changePackageEvent();
        return super.shouldSelectCell(anEvent);
    }

    @Override
    public Object getCellEditorValue() {
        return this.path;
    }

    /**
     * 功能描述：选择包处理器
     */
    private void changePackageEvent() {
        // 包选择器
        final PackageChooserDialog chooser = new PackageChooserDialog("请选择代码生成包", project);
        chooser.show();
        // 选择的包
        PsiPackage selectedPackage = chooser.getSelectedPackage();
        if (selectedPackage == null) {
            return;
        }
        // 选择事件
        this.path = selectedPackage.getQualifiedName();
        this.stopCellEditing();
    }

}
